/**
 * Created with Vim7.3 Mac
 * @fileOverview :
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-06-28 23:13:52
 * @filename : share.js
 * @Last Modified by:   Jim
 * @Last Modified time: 2016-08-26 11:09:54
 */

import {
    AsyncStorage
} from 'react-native';

let Share = {

    getStorage : function(key,func) {
        let callback = func || function(){};
        AsyncStorage.getItem(key)
        .then((value) => {
            if (value !== null){
               callback(true,value);
            } else {
               callback(false,'Initialized with no selection on disk.');
            }
        })
        .catch((error) => callback(false,'AsyncStorage error: ' + error.message));
    },

    setStorage : function(key,value,func) {
        let callback = func || function(){};
        AsyncStorage.setItem(key,value)
        .then(() => {
            Share.resetGolodeStrore(value,key);
            callback(true);
        })
        .catch((error) => {callback(false,'AsyncStorage error: ' + error.message)});
    },

    getAllStorage : function(func) {
        let callback = func || function(){};
        AsyncStorage.getAllKeys()
        .then((value) => {
            return AsyncStorage.multiGet(value);
        })
        .then((arr) => {
            let obj = {};
            if (arr.length > 0) {
                obj = Share.storageArrToObj(arr);
            }
            //console.log(51,obj);
            callback(true,obj);
        })
        .catch((error) => callback(false,'AsyncStorage error: ' + error.message));
    },

    removeItemStorage : function(key,func) {
         let callback = func || function(){};
         AsyncStorage.removeItem(key)
         .then(() => {callback(true)})
         .catch((error) => {callback(false,'AsyncStorage error: ' + error.message)});
    },

    multiRemoveItemStorage : function(arr,func) {
         let callback = func || function(){};
         AsyncStorage.multiRemove(arr)
         .then(() => {callback(true)})
         .catch((error) => {callback(false,'AsyncStorage error: ' + error.message)});

    },

    getAllClearStorage : function(func) {
         let callback = func || function(){};
         AsyncStorage.clear()
         .then(() => {callback(true)})
         .catch((error) => {callback(false,'AsyncStorage error: ' + error.message)});
    },

    setMultiStorage : function(arr,func) {
         let callback = func || function(){};
         AsyncStorage.multiSet(arr)
         .then(() => { 
            Share.resetGolodeStrore(arr);
            callback(true);
         })
         .catch((error) => {callback(false,'AsyncStorage error: ' + error.message)});
    },

    storageArrToObj : function(arr) {
        let obj = {};
        for(i in arr) {
            obj[arr[i][0]] = arr[i][1];
        }
        return obj;
    },

    objToStorageArr : function(obj) {
        let arr =[],str;
        for (i in obj) {
            str =  _.isString(obj[i]) ? obj[i] : JSON.stringify(obj[i]);
            arr.push([i,str]);
        }
        return arr;
    },

    storagePrefix : function(val,prefix) {
        if (_.isArray(val)) {
            val = _.forEach(val,function(n,key) {
                n[0] = prefix+n[0];
            });
        } else {
            val = prefix+val;
        }
        return val;
    },

    resetGolodeStrore : function(val,key) {
        if (_.isArray(val)) {
            val = _.forEach(val,function(value,key) {
                if (key.indexOf('local_') > -1 || key.indexOf('session_') > -1) {
                    Store[value[0]] = value[1];
                }
            });
        } else {
            if (key.indexOf('local_') > -1 || key.indexOf('session_') > -1) {
                    Store[key] = val;
            }   
        }
    },

    getStoreRemoveItem() {
        var arr = [];
        for (var key in Store) {
            if (/^session_.*/.test(key)) {
                arr.push(key);
                delete Store[key];
            }   
        }
        return arr;
    },

    loginOut : function() {
        var arr = this.getStoreRemoveItem();
        Share.multiRemoveItemStorage(arr);
        SceneObj = {};
        this.response = {
            'photo':[],
            'about':[],
            'details':[],
        };
    },

    promiseGetStoreData : function(key){
        return new Promise(function (resolve, reject) {
            Share.getStorage(key,function(bool,value){
                if (bool) {
                    resolve(value);
                } else {
                    reject(value);
                }
            });
        });
    },

    fetchMain : function(opt) {
        opt.url =  Config.APIURL + opt.url;
        this.fetchControl(opt);
    },

    fetchControl : function(opt) {
        let tmps = [], callback = function(){}, data = opt.data ;

        for (let key in data) {
            tmps.push(key + '=' + data[key]);
        }

        let fetchOptions = {
            method: 'POST',
            headers: {
                //'Accept': 'application/json',
                //'Content-Type': 'application/json'
                //'Content-Type': 'multipart/form-data'
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: tmps.join('&')
        };

        fetchOptions = opt.fetchOptions || fetchOptions;
        callback = opt.callback || callback;

        console.log('fetchRequest:',opt,fetchOptions);

        fetch(opt.url, fetchOptions)
        .then((response) => {
            console.log('fetchResponse:',response);
            let data;
            try {
                data = response.json();  
            } catch(e) {
                data = response;
            }
            return data;
        })
        .then((responseData) => {
            callback(responseData);
        })
        .catch((error) => {
            console.log(error);
        })
    },

    getCountryList : function(obj) {
        Share.getStorage('local_country',function(bool,data){
            if (!bool) {
                Share.fetchMain({
                     url : 'get_country_list',
                     callback : function(data) {
                            if (data.results) {
                                Share.setStorage('local_country',JSON.stringify(data.data),function(){
                                    Share.getAllStorage(function(bool,all){global.Store = all;obj.callback(data)});
                                });
                            }
                     }
                  })
            } else {
                obj.callback(data);
            }
        })
    },

    getStateList : function(obj) {
        Share.getStorage('local_state_list"',function(bool,dataObj){
            if (bool) {
                if (dataObj == null || dataObj == undefined || dataObj == '') {
                    dataObj = {};
                } else {
                    dataObj = JSON.parse(dataObj);
                }
            } else {
                dataObj = {};
            }

            let data = dataObj[obj.country];
            if (data == null || data == undefined || data == '') {
                Share.fetchMain({
                    url : 'get_state_list',
                    data: {country:parseInt(obj.country)},
                    callback : function(data) {
                            if (data.results) {
                                dataObj[obj.country] = data.data;
                                Share.setStorage('local_state_list',JSON.stringify(dataObj),function(){
                                    Share.getAllStorage(function(bool,all){global.Store = all;obj.callback(data)});
                                });
                            }
                     }
                })
            } else {
                obj.callback(data);
            }
        })
    },

    analogLogin (data, callback) {
        Share.fetchMain({
            url: 'login',
            data: data,
            callback: function (data) {
                if (typeof (data.errcode) == 'undefined') {
                    Share.setStorage('session_user_id', data.account.usr_id);
                    Share.setStorage(data.account.usr_id, JSON.stringify(data));
                    return true;
                } else {
                    return false;
                }
            }
        }) && callback
    },

    defalutPhoto(gender,img) {

        if(img) {
           img = img.indexOf('woman') > -1 || img.indexOf('man') > -1 || img.indexOf('couple') > -1 ? '' : img;
        }

        if (img == '' || img == undefined || img == null) { 
            if (parseInt(gender) == 2 || parseInt(gender) == 32) {
                img = require('../img/icon_male.png');
            } else if (parseInt(gender) == 1 || parseInt(gender) == 256) {
                img = require('../img/icon_remale.png');
            } else if (parseInt(gender) == 16 || parseInt(gender) == 64) {
                img = require('../img/icon_married.png');
            } else {
                img = require('../img/default_avatar1.png');
            }   
        } else {
            img = {uri: img};
        }
        return img;
    },

    genderToStr(gender,type) {
        let str;
        if (parseInt(gender) == 1) {
            str = 'woman'
        } else if(parseInt(gender) == 2) {
            str = 'man'
        } else {
            str = 'couple';
        }
        if (type == 1) {
            str = str.replace(/(\w)/,function(v){return v.toUpperCase()});
        }
        return str;
    },

    showCheckboxLabel(mid, val, spe, defaultStr) {

        let arr = [], select = JSON.parse(Store[mid]), str = '';
        spe = spe || '; ';

        if (select.length > 0) {
            for (let i in select) {
                if(parseInt(parseInt(val)&parseInt(select[i].value)) > 0) {
                   str += select[i].label + spe;
                }
            }
            str = str.substring(0, str.length - spe.length);
        }

        return str || defaultStr || Lang.common_askMe;
    },

    getLabel(mid, value, defStr) {
        let data = JSON.parse(Store[mid]);
        /*if(data && value) {
            let obj = _.find(data, {value:value} , 'label');
            return obj.label || defStr ||  '';            
        }
        return defStr || '';*/
        let string = defStr;
        data.some((item, index) => {
            if (item.value == value) {
                string = item.label;
                return true;
            }
        });
        return string || '';
    },

    getStateLabel(country, value) {
        let dataObj = JSON.parse(Store.local_state_list);
        if(value && dataObj) {
            let data = dataObj[country];
            let obj = _.find(data, {value:value}, 'label');
            return obj.label || 'All States';      
        }
        return 'All States';

    },

    response : {
        'photo':[],
        'about':[],
        'details':[],

    },

    regResponder(type,name) {
        if (this.response[type]) {
            if (_.indexOf(this.response[type],name) < 0) {
                this.response[type].push(name);
            }
            console.log('regResponder',type,name,this.response);
        } else {
            console.log('First of all need to define type!',type,name);
        }
    },

    notifyResponder(type) {
        if (this.response[type]) {
            _.map(this.response[type], function(n){
                if(SceneObj[n]) {
                   SceneObj[n].responseRender(type);
                }
            });
        } else {
            console.log('First of all need to define type!',type,name);
        }
    },

    repalceStr(str,arr) {
        //str = 'aaa$0bbb$1ccc';
        var patten = new RegExp("\\$\\d{1}","g"),
            newStr = str.replace(patten,function(value){
               var index = parseInt(value.replace('$',''));
               return arr[index];
            });
        return newStr;
    },

    filterValue(value) {
        if (value == null || value == undefined) {
            value = '';
        }
        return value;
    },

    showCheckboxLabel(mid, val, spe, defaultStr) {
        let arr = [],select = JSON.parse(Store[mid]),str = '',spes = spe ? spe : '\n';
        if (select.length > 0) {
            for (var i in select) {
                if(parseInt(parseInt(val)&parseInt(select[i].value)) > 0) {
                   str += select[i].label + spes;
                }
            }
            str = str.substring(0, str.length - spes.length);
        }
        return str || defaultStr || Lang.app_askMe;
    },

    searchSelect(mid, value, defaultStr) {
        var select = JSON.parse(Store[mid]);
        for (var i in select) {
            if (select[i].value == value) {
                return select[i].label;
            }
        }
        return defaultStr || Lang.app_askMe;
    },

    replaceMatchGender(str) {
        if(str != null) {
           str = str.replace(/man/g,"men");
           str = str.replace(/Man/g,"Men");
           str = str.replace(/Couple/g,"Couples");
           str = str.replace(/Cub \/ Men/g,"Cubs / Men");
           str = str.replace(/Cougar/g,"Cougars");
        }
        return str;
    },
};

export default Share;
